<template>
  <v-autocomplete
    v-model="currentVal"
    :loading="loading"
    :items="options"
    :search-input.sync="search"
    item-text="name"
    item-value="id"
    hide-selected
    hide-no-data
    outlined
    :label="label"
    :rules="rules"
    @change="changeHandle"
  ></v-autocomplete>
</template>

<script>
    import {mapState} from 'vuex';

    /**
     * 物料单位选择器
     * @author Canaan
     * @date 2019/8/13 16:30.
     */
    export default {
        name: 'MaterialUnitSelect',
        beforeCreate() {
            this.$store.commit('materialUnitOptions', {cmd: "plusRef"});
            if (this.$store.state.materialUnitOptions.refNum <= 1) {
                this.$store.dispatch('loadMaterialUnitOptions', this);
            }
        },
        mounted() {

        },
        components: {},
        props: {
            value: null,
            label: {
                type: String,
                default: "请选择"
            },
            rules: null
        },
        data() {
            return {
                currentVal: this.value,
                search: null
            }
        },
        computed: {
            ...mapState({
                options: state => state.materialUnitOptions.options,
                loading: state => state.materialUnitOptions.loading,
                refNum: state => state.materialUnitOptions.refNum
            }),
            ...mapState([
                'userContext'
            ])
        },
        methods: {
            changeHandle(val) {
                this.$emit('change', val, this.options.filter(item => {
                    return val === item.id;
                })[0]);
            }
        },
        watch: {
            'userContext.id'() {
                this.$store.dispatch('loadMaterialUnitOptions', this);
            },
            value(val, oldVal) {
                this.currentVal = val;
            },
            currentVal(val, oldVal) {
                this.$emit("input", val);
            }
        },
        filters: {},
        beforeDestroy() {

        },
        destroyed() {
            this.$store.commit('materialUnitOptions', {cmd: "minusRef"});
        }
    }
</script>

<style scoped>

</style>
